package easy.netty.net.core;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author cengy
 */
public class Session
        extends Endpoint
        implements IoSession {

    private static final Logger
            logger = LoggerFactory.getLogger(Session.class);

    protected Entity entity;
    protected Channel channel;
    protected String id;

    @Override
    public void setEntity(Entity entity) {
        this.entity = entity;
    }

    @Override
    public Entity getEntity() {
        return entity;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setChannel(Channel channel) {
        this.channel = channel;
    }

    @Override
    public Channel getChannel() {
        return channel;
    }

    @Override
    public void onOpen() {

    }

    @Override
    public void onClose() {

    }

    @Override
    public void onRead(Object message) {

    }

    @Override
    public void onError(Throwable t) {

    }

    @Override
    public void onEvt(Object evt) {

    }

    @Override
    public void send(Object message) {
        if (null != message)
            send(message, null);
    }

    @Override
    public void send(Object message, SendMessageCallback callback) {
        if (null != message
                && null != channel
                && channel.isWritable()) {

            ChannelFuture future0 = channel.writeAndFlush(message);
            if (callback != null) {
                future0.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {

                        if (future.isSuccess()) {
                            callback.onSuccess(channel, message);
                        } else {
                            callback.onFailure(channel, message, future.cause());
                        }

                    }
                });

                future0.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
            }
        }
    }

    public static class SendMessageCB implements SendMessageCallback {

        @Override
        public void onSuccess(Channel ch, Object message) {

        }

        @Override
        public void onFailure(Channel ch, Object message, Throwable t) {

        }
    }
}
